package cn.yshujia.repository;

import cn.yshujia.constant.SystemConst;
import cn.yshujia.encryption.SMEncrypt;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.util.Map;

@Slf4j
@Component
public class SMRepository {
	
	@Resource
	RedisTemplate<String, String> redis;
	
	private static final Duration OVERDUE = Duration.ofDays(1L);
	
	private static final String PUBLIC_KEY = "sm2:public";
	
	private static final String PRIVATE_KEY = "sm2:private";
	
	private static final String PUBLIC_SECRET = "0437eb7b089007bbf70471cd59a21f84bd2e9616922fb339b05a8639466c262b36682d257a6e318e800a63348789d2b58482cb53ccda6701838be1ae1ca2223c29";
	
	private static final String PRIVATE_SECRET = "aca4d4a7ee4edced1ef5d290b21b979159a263f04e290d5c1fb09c05958ed04e";
	
	private static final Map<String, String> MAP = Map.of(SystemConst.PUBLIC_KEY, PUBLIC_SECRET, SystemConst.PRIVATE_KEY, PRIVATE_SECRET);
	
	public String getPublicKey() {
		String pubKey = redis.opsForValue().get(PUBLIC_KEY);
		if (pubKey == null) {
			Map<String, String> map = SMEncrypt.getSm2Key();
			if (ObjectUtils.isEmpty(map)) {
				set(MAP);
				return PUBLIC_SECRET;
			}
			set(map);
			return map.get(SystemConst.PUBLIC_KEY);
		}
		return pubKey;
	}
	
	public String getPrivateKey() {
		String privateKey = redis.opsForValue().get(PRIVATE_KEY);
		if (privateKey == null) {
			Map<String, String> map = SMEncrypt.getSm2Key();
			if (ObjectUtils.isEmpty(map)) {
				set(MAP);
				return PRIVATE_KEY;
			}
			set(map);
			return map.get(SystemConst.PRIVATE_KEY);
		}
		return privateKey;
	}
	
	
	@Async
	public void set(Map<String, String> map) {
		redis.opsForValue().set(PUBLIC_KEY, map.get(SystemConst.PUBLIC_KEY), OVERDUE);
		redis.opsForValue().set(PRIVATE_KEY, map.get(SystemConst.PRIVATE_KEY), OVERDUE);
	}
}